<?php 
class Category extends CActiveRecord{

	public $cname;
	public $title;
	public $keywords;
	public $pid;
	public $description;
	public $sort;
	public $display;







	public static function model($classname=__CLASS__){
		return parent::model($classname);
	}


	public function tableName(){
		return '{{category}}';
	}
	public function attributeLabels()
	{
		return array(
			'cname'=>'分类名称',
			'title'=>'分类标题',
			'keywords'=>'分类关键字',
			'description'=>'分类描述',
			'sort'=>'分类排序',
			'display'=>'是否显示',
			'pid'=>'所属分类'
		);
	}
	public function rules()
	{
		return array(
			// name, email, subject and body are required
			array('cname, title, keywords, description,sort,pid', 'required','message'=>'必填'),
			array('cname','length','min'=>2,'max'=>8,),
			array('title','length','max'=>40),
			array('sort','numerical'),
			array('sort','check')

			// email has to be a valid email address
			// verifyCode needs to be entered correctly
		);
	}


	///获得所有的分类
	public function getall(){
		$data=$this->findAll();
		return $data;
	}
	//获得所有分类（数组）
	public function getallarray(){
		$sql="select * from {{category}}";
		$com=yii::app()->db->createCommand($sql);
		$data=$com->queryAll();
		return $data;

	}
	public function check(){
		if($this->sort>100||$this->sort<1){
			$this->addError('sort','please input 1-100');
		}
	}
	//无限极分类处理数据
	public function fenlei($data,$pid=0,$level=1){
		$a=array();
		foreach ($data as $k => $v) {
			if($v['pid']==$pid){
				$v['level']=$level;
				$v['html']=str_repeat('--',$level-1);
				$a[]=$v;
				$a=array_merge($a,$this->fenlei($data,$v['cid'],$level+1));
			}
		}
		return $a;

	}
	//获得父类的信息
	public function getpidinfo($cid=0){
		if(!empty($_GET['cid'])){
			$cid=$_GET['cid'];
		}
		$info=$this->find('cid=:cid',array(':cid'=>$cid));
		if(!empty($info)){
			return $info;
		}else{
			$arr=array('cid'=>0,'cname'=>'顶级分类');
			return $arr;
		}

	}
	//删除判断是否有子类
	public function son($cid){
		$num=$this->count('pid=:cid',array(':cid'=>$cid));
		return $num;

	}


}